package com.javacv.plus.extensions.audio.steps;

import com.javacv.plus.core.processor.ProcessorContext;
import com.javacv.plus.core.processor.ProcessorStep;
import com.javacv.plus.extensions.audio.AudioProcessor;
import com.javacv.plus.extensions.audio.AudioResult;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;

/**
 * 音频裁剪步骤
 */
@Slf4j
public class AudioTrimStep implements ProcessorStep<AudioProcessor, AudioResult> {
    private final double startSeconds;
    private final double durationSeconds;

    public AudioTrimStep(double startSeconds, double durationSeconds) {
        this.startSeconds = startSeconds;
        this.durationSeconds = durationSeconds;
    }

    @Override
    public AudioResult execute(AudioProcessor processor, ProcessorContext context) throws Exception {
        log.info("Trimming audio from {}s to {}s", startSeconds, startSeconds + durationSeconds);

        FFmpegFrameGrabber grabber = (FFmpegFrameGrabber) context.getAttribute("grabber");
        try (FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(
                "temp_trim.mp3",
                grabber.getAudioChannels(),
                grabber.getSampleRate()
        )) {
            recorder.setFormat(grabber.getFormat());
            recorder.setAudioBitrate(grabber.getAudioBitrate());
            recorder.setAudioChannels(grabber.getAudioChannels());
            recorder.setSampleRate(grabber.getSampleRate());
            recorder.start();

            // 计算开始和结束的帧位置
            long startFrame = (long) (startSeconds * grabber.getSampleRate());
            long endFrame = (long) ((startSeconds + durationSeconds) * grabber.getSampleRate());
            long currentFrame = 0;

            // 处理音频帧
            Frame frame;
            while ((frame = grabber.grab()) != null) {
                if (currentFrame >= startFrame && currentFrame < endFrame) {
                    recorder.record(frame);
                }

                currentFrame++;
                if (currentFrame >= endFrame) {
                    break;
                }
            }
        }

        // 更新上下文
        context.setAttribute("grabber", new FFmpegFrameGrabber("temp_trim.mp3"));
        log.info("Audio trimming completed");
        return null;
    }

    @Override
    public String getStepName() {
        return "AudioTrim";
    }
} 